<template>
    <div style="height:100%">
      <div>
        <div class='content-title'>
          <div class='content-title-parent'>消息平台</div>
          /
          <div class='content-title-child'>提醒内容字典</div>
        </div>
        <hr class='content-hr'/>
      </div>
      <!--按钮-->
      <el-row class='hotlineClass' style="margin: 10px 0px">
        <el-button type="warning" style="float:right;margin-right:20px" @click="addVisable = true">添加</el-button>
      </el-row>
      <!--表格数据-->
      <el-row>
        <el-table 
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          :data="filterFormFro.tableData" 
          :border="true"
          :row-class-name="tableRowClassName"
          :header-cell-class-name = "tableHeaderClassName"
          v-bind:style="{width: tableWidth + 'px'}">
            <el-table-column prop="messageId" label="消息编号" min-width=15%>
            </el-table-column>
            <el-table-column prop="messageTitle" label="标题内容" min-width=25%>
            </el-table-column>
            <el-table-column prop="content" label="消息内容" min-width=40%>
            </el-table-column>
            <el-table-column label="操作" min-width="20%">
              <template slot-scope="scope" >
                <el-button
                  width="100px"
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!--表格下方分页-->
      <el-row>
        <div class="pagination" style="text-align:center" v-show="paginationVisible">
            <el-pagination
              @current-change="handleCurrentChange"
              background
              :page-size="15"
              :current-page="filterForm.currentPage"
              layout="prev, pager, next"
              :page-count="filterFormFro.totalPage">
            </el-pagination>
        </div>
      </el-row>
      <!-- 添加消息字典信息弹窗 -->
      <el-dialog title="增加内容字典:" :visible.sync="addVisable"
          :closeOnClickModal="false"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          width="550px"
          class="categoryManaDialog"
          @close="resetForm('addForm')">
        <el-form :model='addForm' ref="addForm" label-width="170px" :rules="addRules">
            <el-form-item label="内容编号：" prop="messageId">
              <el-input style='width:240px'  @keyup.native="enterEvent($event,'addForm', 'messageId')" v-model="addForm.messageId"></el-input>
            </el-form-item>
            <el-form-item label="标题名称："  prop="messageTitle">
              <el-input style='width:240px'  clearable v-model.trim="addForm.messageTitle"></el-input>
            </el-form-item>
            <el-form-item label="提醒内容："  prop="content">
              <el-input  type="textarea" :rows="2" style='width:240px' v-model.trim="addForm.content"></el-input>
              <span style="color:#F56C6C;display:block">不超过50字</span>
            </el-form-item>
            <el-form-item label="" >
              <el-button style="width:240px" type="primary" @click="submitAdd()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 编辑内容字典弹窗 -->
      <el-dialog title="编辑内容字典:"  :visible.sync="editVisable"
          :closeOnClickModal="false" 
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          width="550px"
          class="categoryManaDialog"
          @close="resetForm('editForm')">
        <el-form :model='editForm' ref="editForm" label-width="170px" :rules="editRules">
            <el-form-item label="内容编号：" prop="messageId">
              <label>{{editForm.messageId}}</label>
            </el-form-item>
            <el-form-item label="标题名称："  prop="messageTitle">
              <el-input style='width:240px' clearable  v-model.trim="editForm.messageTitle"></el-input>
            </el-form-item>
            <el-form-item label="提醒内容："  prop="content">
              <el-input  type="textarea" :rows="2" style='width:240px' v-model.trim="editForm.content"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-button style="width:240px" type="primary" @click="submitEdit()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
    </div>
</template>
<style>
  .el-table .headerClass {
    background: #f0f9eb;
    text-align: center
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
<script>
import '../../../static/css/businessPlat/common.css'
import '../../../static/css/businessPlat/hotline.css'
import '../../../static/css/businessPlat/remindContent.css'
import apiBus from '../../api/businessPlat/apiBus.js'
export default {
  created () {
    this.getRemindListFro()
  },
  data () {
    var checkHotlineNum = (rule, value, callback) => { // 内容编号验证
      if (/^[A-Z]{2}\d\d\d\d$/.test(value)) {
        callback()
      } else {
        callback(new Error('内容编号为两位大写英文字母+四位流水号'))
      }
    }
    return {
      filterFormFro: {
        tableData: [],
        totalPage: 0
      },
      filterForm: {
        currentPage: 1
      },
      noteVisible: false,
      addForm: {
        messageId: '',
        messageTitle: '',
        content: ''
      },
      loadingText: '正在拼命加载中，请稍等......',
      loading: true,
      tableWidth: '', // 表格宽度
      paginationVisible: false, // 表格下方分页是否显示
      addVisable: false,
      tableData: [],
      editVisable: false,
      editForm: {
        hotLineName: '',
        hotLineNum: '',
        sortNum: '',
        airportName: ''
      },
      deleteForm: {
        hotLineName: '',
        hotLineNum: '',
        sortNum: ''
      },
      addRules: {
        messageId: [
          { required: true, message: '请填写热线编号', trigger: 'blur' },
          { validator: checkHotlineNum, trigger: 'blur' }
        ],
        messageTitle: [
          { required: true, message: '请填写标题名称', trigger: 'blur' },
          { max: 20, message: '标题名称最多20个字', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请填写提醒内容', trigger: 'blur' },
          { max: 50, message: '提醒内容最多50个字', trigger: 'blur' }
        ]
      },
      editRules: {
        messageId: [
          { required: true, message: '请填写热线编号', trigger: 'blur' },
          { validator: checkHotlineNum, trigger: 'blur' }
        ],
        messageTitle: [
          { required: true, message: '请填写标题名称', trigger: 'blur' },
          { max: 20, message: '标题名称最多20个字', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请填写提醒内容', trigger: 'blur' },
          { max: 50, message: '提醒内容最多50个字', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 编号输入框将小写字母转为大写，过滤特殊符号
    enterEvent (ev, form, value) {
      this[form][value] = this[form][value].replace(/[^\w]/g, '')
      this[form][value] = this[form][value].toUpperCase()
    },
    // 重置表单
    resetForm (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    // 增加热线，点击“保存”
    submitAdd () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addRemindListFro()
        } else {
          return false
        }
      })
    },
    // 编辑热线信息，点击“保存”
    submitEdit () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editRemindListFro()
        } else {
          return false
        }
      })
    },
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterForm.currentPage = val
      this.getRemindListFro()
    },
    changeCategory () {
      this.$message.error('分类选择：' + this.filterForm.category)
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    handleEdit (index, row) {
      this.editVisable = true
      this.editForm.messageId = row.messageId.trim()
      this.editForm.messageTitle = row.messageTitle.trim()
      this.editForm.content = row.content.trim()
      console.log(row)
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    setDeleteFro () {
      this.noteVisible = false
      this.$message.success('热线<' + this.deleteForm.hotLineName + '>已删除')
    },
    setEditFro () {
      this.editVisable = false
      this.$message.success('热线<' + this.editForm.hotLineName + '>编辑成功')
    },
    setAddFro () {
      this.addVisable = false
      this.$message.success('热线<' + this.addForm.hotLineName + '>添加成功')
    },
    /** ****************************** 向后台发送请求 ***************************************/
    // 向后台请求提醒策略
    getRemindListFro () {
      this.loading = true
      this.paginationVisible = false
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'messageService_v1'
        }),
        body: JSON.stringify({
          pageSize: 15,
          pageNum: parseInt(this.filterForm.currentPage) // 当前页面数
        })
      }
      this.filterFormFro.tableData = []
      apiBus.getRemindList(para).then(res => {
        this.loading = false
        if (res.data.body.result === 1000) {
          this.filterFormFro.tableData = []
          let resData = res.data.body.content.messages
          if (resData.length > 0) {
            this.$message.success('查询消息字典内容成功！')
            this.filterFormFro.tableData = resData
            for (let i = 0; i < this.filterFormFro.tableData.length; i++) {
              this.filterFormFro.tableData[i].index = (parseInt(this.filterForm.currentPage) - 1) * 15 + i + 1
            }
            this.filterFormFro.totalPage = res.data.body.content.allPages
            this.filterFormFro.totalPage > 1 ? this.paginationVisible = true : this.paginationVisible = false
          } else {
            this.$message.warning('没有相关提醒字典内容！')
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },
    // 向后台增加消息字典内容
    addRemindListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'messageService_v1'
        }),
        body: JSON.stringify({
          messageTitle: this.addForm.messageTitle,
          messageId: this.addForm.messageId,
          content: this.addForm.content
        })
      }
      apiBus.addRemindList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.$message.success('添加消息字典内容成功！')
          this.addVisable = false
          this.filterForm.currentPage = 1
          this.getRemindListFro()
        } else if (res.data.body.result === 4006) {
          this.$message.error('内容编号已存在，请更改')
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 向后台增加消息字典内容
    editRemindListFro () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'messageService_v1'
        }),
        body: JSON.stringify({
          messageTitle: this.editForm.messageTitle,
          messageId: this.editForm.messageId,
          content: this.editForm.content
        })
      }
      apiBus.editRemindList(para).then(res => {
        if (res.data.body.result === 1000) {
          this.$message.success('编辑消息字典内容成功！')
          this.editVisable = false
          this.getRemindListFro()
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    }
  },
  mounted () {
    this.tableWidth = document.body.scrollWidth - 259 - 20
  }
}
</script>